<?php

class TimeHelper
{
    private static $ins;
    private static $timestamp;

    private $Y;
    private $m;
    private $d;
    private $H;
    private $i;
    private $s;

    private function __construct()
    {
    }

    public static function getIns($timestamp = null)
    {
        if (empty(self::$ins)) {
            self::$ins = (new self());
        }
        self::$timestamp = $timestamp ?? time();
        list(self::$ins->Y, self::$ins->m, self::$ins->d, self::$ins->H, self::$ins->i, self::$ins->s) = explode('-', date('Y-m-d-H-i-s', self::$timestamp));
        return self::$ins;
    }

    /**
     * @param $i 0:当前季度 -1：表示前一个季度
     * @return array
     */
    public function getQuarter($i)
    {
        $quarter = ceil(date('m', self::$timestamp) / 3);
        $quarterStartMonth = (($quarter - 1) * 3) + 1;
        $quarterStart = strtotime("{$this->Y}-{$quarterStartMonth}-01 00:00:00");
        $quarterEnd = strtotime('+3 month', $quarterStart) - 1;
        if ($i == 0) {
            return [$quarterStart, $quarterEnd];
        }
        return [strtotime(strval($i * 3) . ' month', $quarterStart), strtotime(strval($i * 3) . ' month', $quarterEnd)];
    }

    public function getYear($i)
    {
        $yearStart = strtotime("{$this->Y}-01-01 00:00:00");
        $yearEnd = strtotime('+1 year', $yearStart) - 1;

        if (0 == $i) {
            return [$yearStart, $yearEnd];
        }
        return [strtotime(strval($i) . ' year', $yearStart), strtotime(strval($i) . ' year', $yearEnd)];
    }

    public function getWeek($i)
    {
        $weekStart = strtotime("this week Monday", self::$timestamp);
        $weekEnd = $weekStart + 604799;
        if (0 == $i) {
            return [$weekStart, $weekEnd];
        }

        return [$weekStart + ($i * 604800), $weekEnd + ($i * 604800)];
    }
}
$helper = TimeHelper::getIns();

list($s, $e) = $helper->getWeek(-1);

var_dump(date('Y-m-d H:i:s', $s), date('Y-m-d H:i:s', $e));
list($s, $e) = $helper->getWeek(-2);
var_dump(date('Y-m-d H:i:s', $s), date('Y-m-d H:i:s', $e));

